package org.cobility;

import java.util.HashSet;
import java.util.Set;

class Solution {
	
	public static void main(String[] args) {
		Solution s = new Solution();
		s.solution(2, new int[] {1, 2, 3, 3, 2, 1, 4});
	}
	
    public int[] solution(int K, int[] T) {
    	Node root = new Node(K);
    	createTree(K, -1, T, root);
    	System.out.println(root);
    	Node maxNode = Node.maxNode;
		System.out.println("MAXNODE: " + maxNode);
		while (maxNode != root) {
			
		}
    	Node parent = maxNode.getParent();
		
    	return null;
    }
    
    private void createTree(int k, int p, int[] t, Node parent) {
    	Set<Integer> children = getChildren(k, p, t);
    	for (int child : children) {
			Node node = new Node(child, parent);
			parent.addChild(node);
			createTree(child, k, t, node);
		}
	}

	private Set<Integer> getChildren(int k, int p, int[] t) {
    	Set<Integer> children = new HashSet<Integer>();
    	if (t[k] != k)
    		children.add(t[k]);
    	for (int i = 0; i < t.length; i++) {
    		if (t[i] == k && i != k) {
				children.add(i);
			}
    	}
    	children.remove(p);
    	return children;
    }
	
}
class Node {
	private int value;
	private int level;
	private Node parent;
	private Set<Node> children = new HashSet<Node>();
	
	public static Node maxNode = new Node(-1);
	
	public Node(int value) {
		this.value = value;
	}

	public Node getParent() {
		return parent;
	}

	public Node(int value, Node parent) {
		this.value = value;
		this.parent = parent;
		this.level = parent.level + 1;
	}
	
	public int getLevel() {
		return level;
	}

	public void addChild(Node child) {
		children.add(child);
		if (maxNode.level < level || (maxNode.level == level && maxNode.value > value)) {
			maxNode = child;
		}
	}

	public void removeChild(Node child) {
		children.remove(child);
	}

	@Override
	public String toString() {
		return "value = " + value  + "; level = " + level + "\n" + children.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + value;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Node other = (Node) obj;
		if (value != other.value)
			return false;
		return true;
	}
}
